package com.itheima.blog.admin.service.impl;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.api.client.blogAdminReport.ReportFeignClient;
import com.itheima.api.client.dto.TBlogDto;
import com.itheima.blog.admin.dao.TCategoryMapper;

import com.itheima.blog.admin.dto.CategoryQuery;
import com.itheima.blog.admin.dto.PageDTO;
import com.itheima.blog.admin.entity.TCategory;
import com.itheima.blog.admin.service.ITCategoryService;
import com.itheima.blog.admin.vo.CategoryVO;
import com.itheima.common.utills.BeanUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 博客分类表 服务实现类
 * </p>
 *
 * @author blog
 * @since 2023-07-11
 */
@Slf4j
@Service
@AllArgsConstructor
public class TCategoryServiceImpl extends ServiceImpl<TCategoryMapper, TCategory> implements ITCategoryService {

    private final ReportFeignClient blogClient;

    @Override
    public PageDTO<CategoryVO> findPage(CategoryQuery categoryQuery) {

        Page<TCategory> page = categoryQuery.toMpPage();
        Page<TCategory> category = lambdaQuery()
                .like(categoryQuery.getName() != null, TCategory::getName, categoryQuery.getName())
                .orderByDesc(TCategory::getTop)
                .orderByDesc(TCategory::getClickCount)
                .page(page);
        List<TCategory> records = category.getRecords();
        List<CategoryVO> voList = new ArrayList<>();
        for (TCategory record : records) {
            CategoryVO categoryVO = BeanUtils.copyBean(record, CategoryVO.class);
            voList.add(categoryVO);
        }
        return PageDTO.of(category, voList);

    }

    @Override
    public void addCategory(TCategory categoryDTO) {
        categoryDTO.setCreateTime(LocalDateTime.now());
        this.save(categoryDTO);
    }

    @Override
    public void updateCategory(TCategory categoryDTO) {
        this.updateById(categoryDTO);

    }

    /*
     * */
    @Override
    public void deleteCategory(List<Long> ids) throws Exception {
        for (Long id : ids) {
            List<TBlogDto> tBlogDtos = blogClient.blogDetail(id);
            if (!tBlogDtos.isEmpty()) {
                throw new Exception("分类下存在文章，无法删除");
            }
            this.removeByIds(ids);
        }

    }

    @Override
    public List<String> contributeForLastYear() {

        List<TCategory> categoryList = lambdaQuery()
                .eq(TCategory::getStatus, 1)
                .orderByDesc(TCategory::getSort).list();

        return categoryList.stream().map(TCategory::getName).collect(Collectors.toList());
    }
}
